package demo.huodongbaoming.controller;

import demo.huodongbaoming.client.CampusActivityClient;
import demo.huodongbaoming.dto.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 校园活动报名控制器
 * 使用OpenFeign客户端调用校园活动报名服务
 */
@RestController
@RequestMapping("/api/campus")
public class CampusActivityController {

    private static final Logger logger = LoggerFactory.getLogger(CampusActivityController.class);

    @Autowired
    private CampusActivityClient campusActivityClient;
    
    /**
     * 获取所有校园活动
     * @return 活动列表
     */
    @GetMapping("/activities")
    public ResponseResult<List<Map<String, Object>>> getAllActivities() {
        logger.info("获取所有校园活动");
        List<Map<String, Object>> activities = campusActivityClient.getAllActivities();
        
        // 检查是否为降级响应
        if (activities.size() == 1 && Boolean.TRUE.equals(activities.get(0).get("isFallback"))) {
            logger.warn("获取活动列表触发服务降级: {}", activities.get(0).get("message"));
            return ResponseResult.fail(503, (String) activities.get(0).get("message"));
        }
        
        logger.info("成功获取活动列表，共{}个活动", activities.size());
        return ResponseResult.success("获取活动列表成功", activities);
    }
    
    /**
     * 获取特定活动详情
     * @param id 活动ID
     * @return 活动详情
     */
    @GetMapping("/activities/{id}")
    public ResponseResult<Map<String, Object>> getActivityById(@PathVariable Long id) {
        logger.info("获取活动详情，ID: {}", id);
        Map<String, Object> activity = campusActivityClient.getActivityById(id);
        
        // 检查是否为降级响应
        if (Boolean.TRUE.equals(activity.get("isFallback"))) {
            logger.warn("获取活动详情触发服务降级: {}", activity.get("message"));
            return ResponseResult.fail(503, (String) activity.get("message"));
        }
        
        logger.info("成功获取活动详情: {}", activity.get("title"));
        return ResponseResult.success("获取活动详情成功", activity);
    }
    
    /**
     * 获取用户报名的活动
     * @param userId 用户ID
     * @return 活动列表
     */
    @GetMapping("/activities/user/{userId}")
    public ResponseResult<List<Map<String, Object>>> getActivitiesByUser(@PathVariable Long userId) {
        logger.info("获取用户报名的活动，用户ID: {}", userId);
        List<Map<String, Object>> activities = campusActivityClient.getActivitiesByUser(userId);
        
        // 检查是否为降级响应
        if (activities.size() == 1 && Boolean.TRUE.equals(activities.get(0).get("isFallback"))) {
            logger.warn("获取用户活动列表触发服务降级: {}", activities.get(0).get("message"));
            return ResponseResult.fail(503, (String) activities.get(0).get("message"));
        }
        
        logger.info("成功获取用户活动列表，共{}个活动", activities.size());
        return ResponseResult.success("获取用户活动列表成功", activities);
    }
    
    /**
     * 获取特定类别的活动
     * @param categoryId 类别ID
     * @return 活动列表
     */
    @GetMapping("/activities/category/{categoryId}")
    public ResponseResult<List<Map<String, Object>>> getActivitiesByCategory(@PathVariable Long categoryId) {
        logger.info("获取特定类别的活动，类别ID: {}", categoryId);
        List<Map<String, Object>> activities = campusActivityClient.getActivitiesByCategory(categoryId);
        
        // 检查是否为降级响应
        if (activities.size() == 1 && Boolean.TRUE.equals(activities.get(0).get("isFallback"))) {
            logger.warn("获取类别活动列表触发服务降级: {}", activities.get(0).get("message"));
            return ResponseResult.fail(503, (String) activities.get(0).get("message"));
        }
        
        logger.info("成功获取类别活动列表，共{}个活动", activities.size());
        return ResponseResult.success("获取类别活动列表成功", activities);
    }
    
    /**
     * 报名参加活动
     * @param activityId 活动ID
     * @param userId 用户ID
     * @return 报名结果
     */
    @PostMapping("/activities/{activityId}/register")
    public ResponseResult<Map<String, Object>> registerForActivity(
            @PathVariable Long activityId,
            @RequestParam Long userId) {
        logger.info("报名参加活动，活动ID: {}，用户ID: {}", activityId, userId);
        Map<String, Object> result = campusActivityClient.registerForActivity(activityId, userId);
        
        // 检查是否为降级响应
        if (Boolean.TRUE.equals(result.get("isFallback"))) {
            logger.warn("活动报名触发服务降级: {}", result.get("message"));
            return ResponseResult.fail(503, (String) result.get("message"));
        }
        
        logger.info("活动报名成功，活动ID: {}，用户ID: {}", activityId, userId);
        return ResponseResult.success("活动报名成功", result);
    }
    
    /**
     * 取消活动报名
     * @param activityId 活动ID
     * @param userId 用户ID
     * @return 取消结果
     */
    @DeleteMapping("/activities/{activityId}/register")
    public ResponseResult<Map<String, Object>> cancelRegistration(
            @PathVariable Long activityId,
            @RequestParam Long userId) {
        logger.info("取消活动报名，活动ID: {}，用户ID: {}", activityId, userId);
        Map<String, Object> result = campusActivityClient.cancelRegistration(activityId, userId);
        
        // 检查是否为降级响应
        if (Boolean.TRUE.equals(result.get("isFallback"))) {
            logger.warn("取消报名触发服务降级: {}", result.get("message"));
            return ResponseResult.fail(503, (String) result.get("message"));
        }
        
        logger.info("取消报名成功，活动ID: {}，用户ID: {}", activityId, userId);
        return ResponseResult.success("取消报名成功", result);
    }
    
    /**
     * 创建新活动
     * @param activity 活动信息
     * @return 创建结果
     */
    @PostMapping("/activities")
    public ResponseResult<Map<String, Object>> createActivity(@RequestBody Map<String, Object> activity) {
        logger.info("创建新活动: {}", activity.get("title"));
        Map<String, Object> result = campusActivityClient.createActivity(activity);
        
        // 检查是否为降级响应
        if (Boolean.TRUE.equals(result.get("isFallback"))) {
            logger.warn("创建活动触发服务降级: {}", result.get("message"));
            return ResponseResult.fail(503, (String) result.get("message"));
        }
        
        logger.info("创建活动成功，ID: {}", result.get("id"));
        return ResponseResult.success("创建活动成功", result);
    }
    
    /**
     * 更新活动信息
     * @param id 活动ID
     * @param activity 活动信息
     * @return 更新结果
     */
    @PutMapping("/activities/{id}")
    public ResponseResult<Map<String, Object>> updateActivity(
            @PathVariable Long id,
            @RequestBody Map<String, Object> activity) {
        logger.info("更新活动信息，ID: {}", id);
        Map<String, Object> result = campusActivityClient.updateActivity(id, activity);
        
        // 检查是否为降级响应
        if (Boolean.TRUE.equals(result.get("isFallback"))) {
            logger.warn("更新活动触发服务降级: {}", result.get("message"));
            return ResponseResult.fail(503, (String) result.get("message"));
        }
        
        logger.info("更新活动成功，ID: {}", id);
        return ResponseResult.success("更新活动成功", result);
    }
    
    /**
     * 获取活动类别列表
     * @return 类别列表
     */
    @GetMapping("/activities/categories")
    public ResponseResult<List<Map<String, Object>>> getActivityCategories() {
        logger.info("获取活动类别列表");
        List<Map<String, Object>> categories = campusActivityClient.getActivityCategories();
        
        // 检查是否为降级响应
        if (categories.size() == 1 && Boolean.TRUE.equals(categories.get(0).get("isFallback"))) {
            logger.warn("获取活动类别列表触发服务降级: {}", categories.get(0).get("message"));
            return ResponseResult.fail(503, (String) categories.get(0).get("message"));
        }
        
        logger.info("成功获取活动类别列表，共{}个类别", categories.size());
        return ResponseResult.success("获取活动类别成功", categories);
    }
    
    /**
     * 获取服务健康状态
     * @return 健康状态信息
     */
    @GetMapping("/health")
    public ResponseResult<Map<String, Object>> getHealthStatus() {
        logger.info("获取服务健康状态");
        Map<String, Object> health = campusActivityClient.getHealthStatus();
        
        // 添加额外信息
        Map<String, Object> result = new HashMap<>(health);
        result.put("checkTime", System.currentTimeMillis());
        
        // 检查是否为降级响应
        if (Boolean.TRUE.equals(health.get("isFallback"))) {
            logger.warn("健康检查触发服务降级: {}", health.get("message"));
        } else {
            logger.info("服务健康状态: {}", health.get("status"));
        }
        
        return ResponseResult.success("获取健康状态成功", result);
    }
} 